package com.module.antiFake.dao;

import java.util.Date;

import org.hibernate.Session;

import base.dao.GenericHibernateDao;

import com.module.antiFake.vo.AntiFakeScanHistory;
import com.module.antiFake.vo.AntiFakeScanTimes;

public class AntiFakeScanTimesDao  extends GenericHibernateDao<AntiFakeScanTimes, Long>{
	private static AntiFakeScanTimesDao dao;
	private static AntiFakeScanHistoryDao antiFakeScanHistoryDao = AntiFakeScanHistoryDao.getInstance();
	
	public synchronized static AntiFakeScanTimesDao getInstance(){
		if(dao == null){
			dao = new AntiFakeScanTimesDao();
		}
		return dao;
	}
	

	/**
	 * 根据扫码记录保存到扫码记录统计表;
	 * @param antiFakeScanHistory
	 */
	public boolean saveOrUpdateForHistory(Session session,AntiFakeScanHistory antiFakeScanHistory) {
		boolean flag =false;
		AntiFakeScanTimes antiFakeScanTimes = getUniqueByProperty(session,"codeInfo",antiFakeScanHistory.getCodeInfo());
		//该码是第一次扫;
		if(antiFakeScanTimes == null){
			antiFakeScanTimes = AntiFakeScanTimes.copyFromAntiFakeScanHistory(antiFakeScanHistory);
			AntiFakeScanTimes secondScanTimes = dao.findUniqueObjectBySQL(session,"from AntiFakeScanTimes times where times.codeInfo='"+antiFakeScanHistory.getSecondCodeInfo()+"'");
			if(secondScanTimes!=null){
				antiFakeScanTimes.setSecondScaned(new Short("1"));
			}
		}
		//该码非第一次扫;
		else{
			antiFakeScanTimes.setTimes(antiFakeScanTimes.getTimes()+1);
			antiFakeScanTimes.setUpdatetime(new Date());
			//读取最近一次扫码时间;
			antiFakeScanHistory.setLastScanDate(antiFakeScanHistoryDao.getLastScanDateFromCode(session,antiFakeScanHistory));
			antiFakeScanHistory.setFirstScanDate(antiFakeScanHistoryDao.getFirstScanDateFromCode(session,antiFakeScanHistory));
		}
		//如果当前是双层码，且是刷了第二层,则设置当前第一层码已刷新;
		if(antiFakeScanHistory.getLayerNum().equals(AntiFakeScanHistory.DOUBLE_LABEL)){
			antiFakeScanTimes.setSecondScaned(new Short("1"));
			AntiFakeScanTimes firstScanTimes = dao.findUniqueObjectBySQL(session,"from AntiFakeScanTimes times where times.codeInfo='"+antiFakeScanTimes.getFirstCodeInfo()+"' and times.layerNum=1");//getUniqueByProperty(session,"firstCodeInfo", antiFakeScanTimes.getFirstCodeInfo());
			if(firstScanTimes!=null){
				firstScanTimes.setSecondScaned(new Short("1"));
				session.save(firstScanTimes);
				flag = true;
			}
			antiFakeScanHistory.setSecondScaned(new Short("1"));
		}
		//如果是第一层码:
		if(antiFakeScanHistory.getLayerNum().equals(AntiFakeScanHistory.ONE_LABEL)){
			antiFakeScanHistory.setSecondScaned(antiFakeScanTimes.getSecondScaned());
		}
		session.save(antiFakeScanTimes);
		antiFakeScanHistory.setTimes(antiFakeScanTimes.getTimes());
		flag = true;
		return flag;
	}

}
